package sandbox.keki.aut.bme.hu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;
import android.widget.Toast;

public class AddPoiAsyncTask extends AsyncTask<String, Void, String> {
	String userID;
	Context context;
	
	public AddPoiAsyncTask(Context context0, String userID0) {
		userID = userID0;
		context = context0;
	}

	@Override
	protected String doInBackground(String... params) {
		String r = "";
		
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("https://social-navigation.appspot.com/pois");
			
			List<NameValuePair> dataPairs = new ArrayList<NameValuePair>(2);
			dataPairs.add(new BasicNameValuePair("action", "ADD"));
			dataPairs.add(new BasicNameValuePair("userID", userID));
			dataPairs.add(new BasicNameValuePair("name", params[0]));
			dataPairs.add(new BasicNameValuePair("latitude", params[1]));
			dataPairs.add(new BasicNameValuePair("longitude", params[2]));
			dataPairs.add(new BasicNameValuePair("description", params[3]));			
			
			httppost.setEntity(new UrlEncodedFormEntity(dataPairs, "UTF-8"));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			BufferedReader resp = new BufferedReader(new InputStreamReader(entity.getContent()));
			String line = resp.readLine();
			if (line != null){
				r = line;
			} else {
				r = "No response arrived form server!";
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			r = "Exception happened!";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			r = "Exception happened!";
		} finally {
			return r;
		}
	}

	@Override
	protected void onPostExecute(String resp) {
		super.onPostExecute(resp);
		Toast.makeText(context, resp, Toast.LENGTH_SHORT).show();
	}
}
